package user

import (
	"context"
	"errors"
	"time"

	"go-zero_try/mall/order/api/internal/svc"
	"go-zero_try/mall/order/api/internal/types"
	"go-zero_try/mall/order/rpc/pb/pb"
	"go-zero_try/mall/order/util"
	"go-zero_try/model"

	"github.com/golang-jwt/jwt"
	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogic) UserLogin(req *types.LoginReq) (resp *types.JwtReps, err error) {
	if len(req.UID) < 4 {
		return nil, util.NewCodeError(util.ParameterError, "用户名非法")
	}
	if len(req.Pwd) < 6 {
		return nil, util.NewCodeError(util.ParameterError, "密码非法")
	}

	userResp, err := l.svcCtx.UserClient.Login(l.ctx, &pb.LoginReq{
		UID:      req.UID,
		Password: req.Pwd,
	})
	switch err {
	case nil:
		if userResp.Pwd != req.Pwd {
			return nil, err
		}
		now := time.Now().Unix()
		accessExpire := l.svcCtx.Config.JwtAuth.AccessExpire
		jwtToken, err := l.getJwtToken(l.svcCtx.Config.JwtAuth.AccessSecret, now, accessExpire, userResp.UID)
		if err != nil {
			return nil, util.NewCodeError(util.Error, "失败")
		}

		l.svcCtx.Redis.Set("loginUserId:"+userResp.UID, userResp.Name+";"+userResp.Age+";", time.Duration(accessExpire)*time.Second)
		l.svcCtx.Redis.Do("SADD", "loginStatus", userResp.UID)

		return &types.JwtReps{
			Msg: userResp.Msg,
			Token: map[string]interface{}{
				"UID":         userResp.UID,
				"Username":    userResp.Name,
				"Age":         userResp.Age,
				"token":       jwtToken,
				"ExprieTime":  now + accessExpire,
				"RefreshTime": now + accessExpire/2,
			},
		}, nil
	case model.ErrNotFound:
		return nil, errors.New("用户未注册")
	default:
		return nil, errors.New("用户未注册")
	}
}

func (l *UserLoginLogic) getJwtToken(secretKey string, iat, seconds int64, userId string) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	claims["userId"] = userId
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}
